package com.bdqn.blog.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bdqn.blog.entity.ListSong;
import com.bdqn.blog.entity.Singer;
import com.bdqn.blog.entity.Song;
import com.bdqn.blog.mapper.ListSongMapper;
import com.bdqn.blog.service.impl.ListSongServiceImpl;
import com.bdqn.blog.service.impl.SingerServiceImpl;
import com.bdqn.blog.service.impl.SongServiceImpl;
import com.bdqn.blog.util.Result;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * <p>
 * 歌曲 前端控制器
 * </p>
 *
 * @author 阿桐幕
 * @since 2020-10-29
 */
@RestController
@RequestMapping("/blog/song")
@Api("歌曲操作接口")
public class SongController {

    @Autowired
    SongServiceImpl songService;

    @Autowired
    SingerServiceImpl singerService;

    @Autowired
    ListSongServiceImpl listSongService;

    /**
     * 更新歌曲图片
     */
    @ApiOperation("更新歌曲图片接口")
    @PostMapping("/SaveSongImg")
    public Object SaveSongImg(@ApiParam("歌曲图片文件")@RequestParam("file") MultipartFile avatorFile, @ApiParam("歌曲id") @RequestParam("id")int id){
        System.out.println(id+"==================>>>>>>>");
        if(avatorFile.isEmpty()){
            return Result.fail( "图片上传失败");
        }
        //文件名=当前时间到毫秒+原来的文件名
        String fileName = System.currentTimeMillis()+avatorFile.getOriginalFilename();
        //文件路径F:\idea-project\music\src\main\resources\static\img\singerPic
        //文件路径
        String filePath = System.getProperty("user.dir")+System.getProperty("file.separator")+"img"
                +System.getProperty("file.separator")+"songPic";
        //如果文件路径不存在，新增该路径
        File file1 = new File(filePath);
        if(!file1.exists()){
            file1.mkdir();
        }
        //实际的文件地址
        File dest = new File(filePath+System.getProperty("file.separator")+fileName);
        //存储到数据库里的相对文件地址
        String storeAvatorPath = "/img/songPic/"+fileName;
        try {
            avatorFile.transferTo(dest);
            Song song = new Song();
            song.setId(id);
            song.setPic(storeAvatorPath);
            boolean flag = songService.saveOrUpdate(song);
            if(flag){
                return Result.success("上传成功");
            }
            return Result.fail( "图片上传失败");
        } catch (IOException e) {

            return Result.fail( "图片上传失败")+e.getMessage();
        }
    }
    /**
     * 更新歌曲
     */
    @ApiOperation("更新歌曲接口")
    @PostMapping("/SaveSongUrl")
    public Object SaveSongUrl(@ApiParam("歌曲文件")@RequestParam("file") MultipartFile avatorFile,@ApiParam("歌曲id") @RequestParam("id")int id){
        if(avatorFile.isEmpty()){
            return Result.fail( "歌曲上传失败");
        }
        //文件名=当前时间到毫秒+原来的文件名
        String fileName = System.currentTimeMillis()+avatorFile.getOriginalFilename();
        //文件路径F:\idea-project\music\src\main\resources\static\img\singerPic
        //文件路径
        String filePath = System.getProperty("user.dir")+System.getProperty("file.separator")+"song";
        //如果文件路径不存在，新增该路径
        File file1 = new File(filePath);
        if(!file1.exists()){
            file1.mkdir();
        }
        //实际的文件地址
        File dest = new File(filePath+System.getProperty("file.separator")+fileName);
        //存储到数据库里的相对文件地址
        String storeAvatorPath = "/song/"+fileName;
        try {
            avatorFile.transferTo(dest);
            Song song = new Song();
            song.setId(id);
            song.setUrl(storeAvatorPath);
            boolean flag = songService.saveOrUpdate(song);
            if(flag){
                return Result.success("上传成功");
            }
            return Result.fail( "歌曲上传失败");
        } catch (IOException e) {

            return Result.fail( "歌曲上传失败")+e.getMessage();
        }
    }

    @GetMapping("/findSingAllOrByName")
    @ApiOperation("查询接口")
    public Object findSingerAllOrByName(String query , Integer pageIndex , Integer pageSize,Integer singerId){
        //封装pagehelper的分页对象  参数 页面 页大小
        PageHelper.startPage(pageIndex,pageSize);
        List<Song> singerList = songService.findSongAllOrByName(query,singerId);
        //将集合存入到pageinfo对象中
        PageInfo<Song> pageInfo = new PageInfo<Song>(singerList);
        return Result.success(pageInfo);
    }

    // 歌单中的歌曲查询
    @GetMapping("/findSongAllOrByNameAndid")
    public Object findSongAllOrByNameAndid(String query ,Integer SongListid ,Integer pageIndex , Integer pageSize){
        //封装pagehelper的分页对象  参数 页面 页大小
        PageHelper.startPage(pageIndex,pageSize);
        List<Song> singerList = songService.findSongAllOrByNameAndid(query,SongListid);
        //将集合存入到pageinfo对象中
        PageInfo<Song> pageInfo = new PageInfo<Song>(singerList);
        return Result.success(pageInfo);
    }

    @GetMapping("/getAll")  //查询某歌手的全部歌曲
    public Result getAll(Integer singerId){
        QueryWrapper<Song> wrapper = new QueryWrapper<>();
        wrapper.eq("singer_id",singerId);
        return Result.success(songService.list(wrapper));
    }

    @GetMapping("/getAlls") //查询某歌单的全部歌曲
    public Result getAlls(Integer SongListid){
        return Result.success(songService.getallByid(SongListid));
    }

    @GetMapping("/getSonglistAll")  //查询全部歌曲
    public Result getSonglistAll(){
        return Result.success(songService.list());
    }


    @PostMapping("/getSongByid/{id}")
    public Result getSongByid(@PathVariable Integer id){
        return Result.success(songService.getById(id));
    }

    @GetMapping("/getSongByName")   //按歌曲名来模糊查询
    public Result getSongByName(String name){
        QueryWrapper<Song> wrapper = new QueryWrapper<>();
        wrapper.like("name",name);
        return Result.success(songService.list(wrapper));
    }

    @PostMapping("/delSongByd/{id}")
    public Result delSingerByd(@PathVariable Integer id){
        return Result.success(songService.removeById(id));
    }

    @PostMapping("/SaveSong")
    public Result SaveSong(@RequestBody Song song){
        boolean b = songService.saveOrUpdate(song);
        if (b){
            return Result.success();
        }else {
            return Result.fail("修改失败");
        }
    }


    /**
     * 添加歌曲
     */
    @PostMapping("/addSong")
    public Object addSong(HttpServletRequest request, @RequestParam("file") MultipartFile avatorFile){
        String singerId = request.getParameter("singerId").trim();  //所属歌手id
        String name = request.getParameter("name").trim();          //歌名
        String introduction = request.getParameter("introduction").trim();          //简介
        String pic = "/img/songPic/tubiao.jpg";                     //默认图片
        String lyric = request.getParameter("lyric").trim();     //歌词

        System.out.println((avatorFile == null)  +"============>>>>>>>");
        if(avatorFile.isEmpty()){
            return Result.fail( "歌曲上传失败");
        }
        //文件名=当前时间到毫秒+原来的文件名
        String fileName = System.currentTimeMillis()+avatorFile.getOriginalFilename();
        //文件路径F:\idea-project\music\src\main\resources\static\img\singerPic
        //文件路径
        String filePath = System.getProperty("user.dir")+System.getProperty("file.separator")+"song";
        //如果文件路径不存在，新增该路径
        File file1 = new File(filePath);
        if(!file1.exists()){
            file1.mkdir();
        }
        //实际的文件地址
        File dest = new File(filePath+System.getProperty("file.separator")+fileName);
        System.out.println(dest);
        //存储到数据库里的相对文件地址
        String storeAvatorPath = "/song/"+fileName;

        Song song = new Song();
        song.setSingerId(Integer.parseInt(singerId));
        song.setName(name);
        song.setIntroduction(introduction);
        song.setPic(pic);
        song.setLyric(lyric);
        song.setUrl(storeAvatorPath);
        try {
            avatorFile.transferTo(dest);  //执行上传文件
            boolean flag = songService.save(song);
            if(flag){
                return Result.success("添加成功");
            }
            return Result.fail( "歌曲上传失败");
        } catch (Exception e) {
            return Result.fail( "歌曲上传失败")+e.getMessage();
        }
    }

    /**
     * 添加歌曲 和 添加歌单包含歌曲列表
     */
    @PostMapping("/addSong_Song_list_id")
    public Object addSong_Song_list_id(HttpServletRequest request, @RequestParam("file") MultipartFile avatorFile){
        String name = request.getParameter("name").trim();          //歌名
        String SingerName = request.getParameter("SingerName").trim();          //歌名


        String pic = "/img/songPic/tubiao.jpg";                 //默认图片
        String lyric  = request.getParameter("lyric").trim();          //歌名
        //歌单id
        Integer song_list_id = Integer.parseInt(request.getParameter("SongListid").trim());
        if(avatorFile.isEmpty()){
            return Result.fail( "歌曲上传失败");
        }
        //文件名=当前时间到毫秒+原来的文件名
        String fileName = System.currentTimeMillis()+avatorFile.getOriginalFilename();
        //文件路径
        String filePath = System.getProperty("user.dir")+System.getProperty("file.separator")+"song";
        //如果文件路径不存在，新增该路径
        File file1 = new File(filePath);
        if(!file1.exists()){
            file1.mkdir();
        }
        //实际的文件地址
        File dest = new File(filePath+System.getProperty("file.separator")+fileName);
        System.out.println(dest);
        //存储到数据库里的相对文件地址
        String storeAvatorPath = "/song/"+fileName;
        //  歌曲对象
        Song song = new Song();
        song.setName(name);
        song.setPic(pic);
        song.setUrl(storeAvatorPath);
        song.setLyric(lyric);
        try {
            List<Singer> singers = singerService.list(new QueryWrapper<Singer>().eq("name", SingerName));
            if(!(singers.get(0).getName().equals(SingerName))){
                return Result.fail( "抱歉,这个歌手不存在");
            }
            avatorFile.transferTo(dest);  //执行上传文件
            song.setSingerId(singers.get(0).getId());;  //保存歌手id
            boolean flag = songService.save(song);
            if(flag){
                //歌单歌曲列表对象
                ListSong listSong = new ListSong();
                listSong.setSongId(song.getId());
                listSong.setSongListId(song_list_id);
                listSongService.save(listSong);

                return Result.success("添加成功");
            }
            return Result.fail( "歌曲上传失败");
        } catch (Exception e) {
            return Result.fail( "歌曲上传失败")+e.getMessage();
        }
    }


}

